<?php

class FileLog {

  private $file = "log.txt";
  private $error = null;

  private $file_handle = null;
  private $error_handle = null;
  
  public function file($file = null) {
    if( is_null($file) ) { return $this->file; }
    if( (file_exists($file) && !is_writable($file)) || !is_writable(dirname($file)) ) throw new Exception("No se puede escribir en el archivo de log: ".$file);

    $this->file = $file;
    return $this;
  }
  
  public function errorFile($file = null) {
    if( is_null($file) ) { return $this->error; }
    if( (file_exists($file) && !is_writable($file)) || !is_writable(dirname($file)) ) throw new Exception("No se puede escribir en el archivo de log de errores: ".$file);

    if($file != $this->file) {
      $this->error = $file;
    }
  }
  
  private function openLogFile() {
    if(is_null($this->file_handle)) {
      $this->file_handle = fopen($this->file, "a+");
      $this->logRegisterDate();
    }
  }
  
  private function openErrorFile() {
    if(is_null($this->error_handle)) {
      if(is_null($this->error) || $this->error == $this->file) {
        $this->error_handle = $this->file_handle;
      } else {
        $this->error_handle = fopen($this->error, "a+");
      }
    }
  }
  
  public function log($message) {
    $this->openLogFile();

    fwrite($this->file_handle, $message . "\r\n");
    return $message . "\n";
  }
  
  public function error($message) {
    $this->openErrorFile();
    $this->errorRegisterDate();

    fwrite($this->error_handle, $message . "\r\n");
    return $message . "\n";
  }
  
  public function __destruct() {
    if( !is_null($this->file_handle) ) { fclose($this->file_handle); }
    if( !is_null($this->error_handle) ) { fclose($this->error_handle); }
  }

  public function logRegisterDate() {
    if(!isset($this->logDateRegistered)){
      $this->log("==========================================");
      $this->log(date("Y-m-d"));
      $this->logDateRegistered = true;
      if(is_null($this->error) || $this->error == $this->file) {
        $this->errorDateRegistered = true;
      }
    }
  }

  public function errorRegisterDate() {
    if(!isset($this->logDateRegistered)){
      $this->error(date("Y-m-d"));
      $this->errorDateRegistered = true;
    }
  }
  
}